`
https://leetcode.cn/problems/binary-subarrays-with-sum/
`

/**
 * @param {number[]} nums
 * @param {number} goal
 * @return {number}
 */
var numSubarraysWithSum = function (nums, goal) {
  // >= goal 的个数 - >= goal + 1 的个数就是答案
  return solve(nums, goal) - solve(nums, goal + 1)
};

// 计算有多少个和 >= goal 的非空子数组
function solve(nums, goal) {
  const n = nums.length
  let sum = 0
  let res = 0
  let left = 0, right = 0

  while (right < n) {
    const n1 = nums[right++]
    sum += n1

    while (left < right && sum >= goal) {
      const n2 = nums[left++]
      sum -= n2
    }

    res += left
  }

  return res
}